package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.BusinessTool;
import com.csjy.migration.hnnd.DbUtil;
import com.csjy.migration.hnnd.ProgramArgument;
import com.csjy.migration.hnnd.Tool;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;

import javax.script.ScriptException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程附件表
 */
@BusinessDataConverter(
    auto = false,

    insertSql = "INSERT INTO ND_PROJECT_AFFIX_SUBMIT\n" +
        "(ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, PROJECT_ID, FILE_NAME, STORE_TYPE, FILE_SIZE, SUBMITTER, FILE_CONTENT, FILE_REMARK, FILE_URL, AFFIX_TYPE, MODULE_ID, FILE_TYPE, AFFIX_SOURCE, BIZ_TYPE, IS_DELETE, TASK_ID, PROC_ID, FILE_STATUS, LETTER_NUM, PROJECT_ATTACHMENT_TYPE, SOURCEID)\n" +
        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",

    updateSql = "UPDATE ND_PROJECT_AFFIX_SUBMIT\n" +
        "SET CREATE_NAME=?, CREATE_BY=?, CREATE_DATE=?, UPDATE_NAME=?, UPDATE_BY=?, UPDATE_DATE=?, SYS_ORG_CODE=?, SYS_COMPANY_CODE=?, BPM_STATUS=?, PROJECT_ID=?, FILE_NAME=?, STORE_TYPE=?, FILE_SIZE=?, SUBMITTER=?, FILE_CONTENT=?, FILE_REMARK=?, FILE_URL=?, AFFIX_TYPE=?, MODULE_ID=?, FILE_TYPE=?, AFFIX_SOURCE=?, BIZ_TYPE=?, IS_DELETE=?, TASK_ID=?, PROC_ID=?, FILE_STATUS=?, LETTER_NUM=?, PROJECT_ATTACHMENT_TYPE=?, SOURCEID=?\n" +
        "WHERE ID = ?",

    findMigratedIdListSql = "SELECT ID FROM ND_PROJECT_AFFIX_SUBMIT WHERE PROC_ID = ?"
)
public class NdProjectAffixSubmit extends AbstractWorkflowBusiness {

  private String bizType = null;
  private Map<String, Map<String, Object>> taskParamMap = null;
  private NdProjectAffix ndProjectAffix = null;
  public void setTaskParamMap(Map<String, Map<String, Object>> taskParamMap) {
    this.taskParamMap = taskParamMap;
  }

  public void setBizType(String bizType) {
    this.bizType = bizType;
  }

  public NdProjectAffixSubmit(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId, String procInstId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
    ndProjectAffix = new NdProjectAffix(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId);
  }

  @Override
  public void migrate() throws Exception {
    for(Map row : this.sourceData.getWfFileObjList()) {
      if(!row.get("PROCID").toString().equals(this.procInstId)) {
        continue;
      }
      try {
        // 判断是否需要覆盖迁移
        int needMigratedResult = this.needMigrated(row.get("FILEID").toString());
        if(needMigratedResult == 0) {
          continue;
        }

        // 单条插入或更新
        List values = this.buildValues(row);
        ArrayList ndProjectAffixValues = (ArrayList) ((ArrayList)values).clone();

        if(needMigratedResult == 1) {
            this.targetDbUtil.updateByParams(updateSql,values,true);
        } else {
            this.targetDbUtil.updateByParams(insertSql,values);
        }

       // IS_VALID
        ndProjectAffixValues.set(26, null);
        // LETTER_NUM
        ndProjectAffixValues.set(27,row.get("SORTNO"));
        // CONTRACT_NUM
        ndProjectAffixValues.set(28,row.get("CONTRACTSERIALNO"));
        // PROJECT_ATTACHMENT_TYPE
        ndProjectAffixValues.set(ndProjectAffixValues.size() - 1, 1);

         ndProjectAffix.customMigrate(ndProjectAffixValues);
      } catch(Exception e) {
        throw new Exception(String.format("流程实例[%s]-流程附件迁移失败:%s\n",this.procInstId, e.getMessage()));
      }
    }
    ndProjectAffix.customStart();
  }

  public List buildValues(Map row) throws ScriptException {
    String[] originalFileNameArr = row.get("FILENAME").toString().split("\\.");
    Map<String,Object> singleTaskParamMap = this.taskParamMap.get(row.get("TASKID").toString());
    Object rowEmpCode = row.get("EMPCODE");
    String empCode = BusinessTool.getTaskRealActorId((rowEmpCode == null || rowEmpCode.toString().equals("")) ? null
        : rowEmpCode.toString(),row.get("CREATE_TIME"));
    List values = new ArrayList();
    // ID
    values.add(row.get("FILEID").toString());
    // CREATE_NAME
    values.add(BusinessTool.getEmpNameByEmpCode(empCode));
    // CREATE_BY
    values.add(empCode);
    // CREATE_DATE
    values.add(row.get("CREATE_TIME"));
    // UPDATE_NAME 临时作为存储合同编号
    values.add(null);
    // UPDATE_BY
    values.add("jwfile");
    // UPDATE_DATE
    values.add(row.get("MODIFY_TIME"));
    // SYS_ORG_CODE
    values.add(null);
    // SYS_COMPANY_CODE
    values.add("002");
    //BPM_STATUS
    values.add(1);
    //PROJECT_ID
    values.add(this.projectId);
    //FILE_NAME
    values.add(Tool.decodeUnicode(row.get("FILENAME")));
    // TODO:STORE_TYPE 存储形式(电子件、原纸件、复印件) 新系统中都为0 或 null
    values.add(null);
    // FILE_SIZE (MB) 保留两位小数
    try {
      BigDecimal originalFileSize = (BigDecimal)row.get("FILESIZE");
      values.add(originalFileSize.divide(BigDecimal.valueOf(1024*1024)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
    } catch(Exception e) {
      values.add(null);
    }
    // SUBMITTER
    values.add(null);
    // FILE_CONTENT
    values.add(null);
    // FILE_REMARK
    values.add(Tool.decodeUnicode(row.get("FILEREMARK")));
    // FILE_URL
    values.add(row.get("FILESTORENAME").toString());
    // AFFIX_TYPE
    if(singleTaskParamMap !=null) {

      Object affixType = singleTaskParamMap.get("affixTypeCommon");
      if (singleTaskParamMap.get("fileId") != null) {
        if (singleTaskParamMap.get("fileId").toString().equals(row.get("FILEID").toString())) {
          affixType = singleTaskParamMap.get("affixType");
        }
      }
      values.add(affixType);
    }else {
      values.add(null);
    }
    // MODULE
    values.add(row.get("TASKID")+"-JW");
    // FILE_TYPE
    values.add(originalFileNameArr[originalFileNameArr.length - 1]);
    // TODO:AFFIX_SOURCE
    values.add(null);
    // BIZ_TYPE
    values.add(bizType);
    // IS_DELETE
    values.add(0);
    // TASK_ID
    values.add(row.get("TASKID").toString() + "-JW");
    // PROC_ID
    values.add(this.procInstId + "-JW");
    // FILE_STATUS
    values.add(1);
    // LETTER_NUM
    values.add(row.get("SORTNO"));
    // PROJECT_ATTACHMENT_TYPE(1:基础资料 2:征信资料 3:土地资料)
    values.add(1);
    // SOURCE_ID
    values.add(row.get("FILEID"));

    return values;
  }

}
